package com.osmino.contacts.search;

import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.osmino.contacts.IntentsTable;
import com.osmino.contacts.R;
import com.osmino.contacts.entity.Contact;
import com.osmino.contacts.provider.ContactsContractQueries;
import com.osmino.core.AbsListActivity;
import com.osmino.core.DialogGenerator;

public final class SearchDublicatesActivity extends AbsListActivity implements ISearchDublicateController {

	private DialogGenerator mDialogGenerator;
	private DublicateAdapter mAdapter;
	private TextView mHeaderText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.merge_dublicate_layout);
		mHeaderText = (TextView) findViewById(R.id.dublicates_found);
		mDialogGenerator = new DialogGenerator(this, this);
		mAdapter = new DublicateAdapter(this, this);
		setListAdapter(mAdapter);
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		int searchMode = getIntent().getIntExtra(IntentsTable.EXTRA_MERGE_AUTOMATIC, IntentsTable.EXTRA_MERGE_BY_NAME);
		List<Contact> contacts = mHostApplication.getContactsContractResolver().getListContacts();
		AsyncDublicatesSearcher command = getCommandByMode(contacts, searchMode);
		command.execute();
		prepTitle();
	}
	
	private void prepTitle(){
		findViewById(R.id.title_bar_add_icon).setVisibility(View.INVISIBLE);
		findViewById(R.id.title_bar_edit_icon).setVisibility(View.INVISIBLE);
		((TextView)findViewById(R.id.title_bar_text)).setText(R.string.merge);	
		int wrapContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(wrapContent, wrapContent);
		params.addRule(RelativeLayout.CENTER_IN_PARENT);
		findViewById(R.id.title_bar_text).setLayoutParams(params);
		//initialized with zero for a case
		String text = getString(R.string.found_n_duplicates);
		String.format(text, 0);
		mHeaderText.setText(text);
	}
	
	private AsyncDublicatesSearcher getCommandByMode(List<Contact>contacts, int searchMode) {
		AsyncDublicatesSearcher command = null;
		switch (searchMode) {
			case IntentsTable.EXTRA_MERGE_BY_NAME:
				command = new AsyncDublicatesDisplayNameSearcher(this, contacts);
				break;
			case IntentsTable.EXTRA_MERGE_BY_EMAIL:
				command = new AsyncDublicatesEmailSearcher(this, contacts);
				break;
			case IntentsTable.EXTRA_MERGE_BY_PHONE:
				command = new AsyncDublicatesPhonesSearcher(this, contacts);
				break;
		}
		return command;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
			case R.id.dialog_waiting:
				dialog = mDialogGenerator.createWaitingDialog();
				break;
			case R.id.dialog_quick_message:
				dialog = mDialogGenerator.createQuickMessageDialog(null, null);
				break;
			default:
				dialog = super.onCreateDialog(id);
		}
		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case R.id.dialog_quick_message:
				mDialogGenerator.prepareQuickMessageDialog((AlertDialog) dialog);
				break;
			default:
				super.onPrepareDialog(id, dialog);
		}
	}

	@Override
	public void onMergeDuplicateClick(int section, String constraint) {
		int startIndex = mAdapter.getPositionForSection(section) + 1;
		int endIndex = mAdapter.getPositionForSection(section + 1);
		if (endIndex <= 0) {
			endIndex = mAdapter.getCount();
		}
		List<Contact> listContacts = new ArrayList<Contact>();
		for (int i = startIndex; i < endIndex; i++) {
			boolean checked = getListView().isItemChecked(i);
			if (checked) {
				Contact contact = (Contact) mAdapter.getItem(i);
				listContacts.add(contact);
			}
		}
		if (listContacts.size() < 2) {
			mDialogGenerator.setDialogTitle(R.id.dialog_quick_message, getString(R.string.merge_error_title));
			mDialogGenerator.setDialogText(R.id.dialog_quick_message, getString(R.string.merge_error_text));
			showDialog(R.id.dialog_quick_message);
		} else {
			Contact mainContact = listContacts.remove(0);
			ContactsContractQueries.mergeContacts(this, mainContact, listContacts, constraint);
			finish();
		}
	}

	@Override
	public void onDublicatesSearchStart() {
		showDialog(R.id.dialog_waiting);
	}

	@Override
	public void onDublicatesFound(List<SearchStructure> listSearchStructures) {
		String text = getString(R.string.found_n_duplicates);
		text = String.format(text, listSearchStructures.size());
		mHeaderText.setText(text);
		mAdapter.setListSearchStructures(listSearchStructures);
	}
	
	@Override
	public void onEditConstraint(int section, String constraint) {
		mAdapter.setNewConstraintForSection(section, constraint);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search_dublicates_option_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		int searchMode = IntentsTable.EXTRA_MERGE_BY_NAME;
		switch (itemId) {
			case R.id.contact_option_search_by_name:
				searchMode = IntentsTable.EXTRA_MERGE_BY_NAME;
				break;
			case R.id.contact_option_search_by_email:
				searchMode = IntentsTable.EXTRA_MERGE_BY_EMAIL;
					break;
			case R.id.contact_option_search_by_phone:
				searchMode = IntentsTable.EXTRA_MERGE_BY_PHONE;
				break;
		}
		List<Contact> contacts = mHostApplication.getContactsContractResolver().getListContacts();
		AsyncDublicatesSearcher command = getCommandByMode(contacts, searchMode);
		command.execute();
		return false;
	}
}
